package dev.xesam.androidkit.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

public final class ClientUtil {

    private static final String FIRST_SRC = "first_src";
    private static final String LAST_SRC = "UMENG_CHANNEL";
    private static final String SRC_UNKNOWN = "src_unknown";

    public static String getFirstSrc(Context context) {
        String firstSrc = StorageUtil.getPseudoPersistValue(context, FIRST_SRC);
        if (TextUtils.isEmpty(firstSrc)) {

            int versionCode = 0;
            try {
                PackageManager pm = context.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(
                        context.getPackageName(), 0);
                versionCode = pi.versionCode;
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (versionCode <= 20) {
                firstSrc = SRC_UNKNOWN;
            } else {
                firstSrc = getLastSrc(context);
            }
            StorageUtil.setPseudoPersistValue(context, FIRST_SRC, firstSrc);
        }
        return firstSrc;
    }

    public static String getLastSrc(Context context) {
        return getFromApplication(context, LAST_SRC);
    }

    private static String getFromApplication(Context context, String name) {

        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return info.metaData.getString(LAST_SRC);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return SRC_UNKNOWN;
        }
    }
}
